const UIComponentClass = "eui.UIComponent";

/**
 * 自定义的流式布局
 */
class FlowLayout extends eui.LayoutBase {

	/**
	 * 左边距
	 */
	private $paddingLeft: number = 0;

	/**
	 * 上边距
	 */
	private $paddingTop: number = 0;

	/**
	 * 水平间隔
	 */
	private $hGap: number = 0;

	/**
	 * 垂直间隔
	 */
	private $vGap: number = 0;

	/**
	 * 行的数目
	 */
	private $numRows: number = 0;

	public constructor() {
		super();
	}

	public measure() {
		super.measure();
		//我也不想用常量的，只是这里一直获取不到width的值，没办法
		let measuredWidth = 666, measureHeight = this.$paddingTop;
		let accumulateLeft = this.$paddingLeft;
		let maxHeightInRow = 0;
		let bounds = egret.$TempRectangle;
		for (var i: number = 0; i < this.target.numChildren; i++) {
			var layoutElement: eui.UIComponent = <eui.UIComponent>(this.target.getElementAt(i));
			layoutElement.getPreferredBounds(bounds);
			if (accumulateLeft + bounds.width <= measuredWidth) {
				maxHeightInRow = Math.max(maxHeightInRow, bounds.height);
			} else {
				measureHeight += maxHeightInRow + this.$vGap;
				accumulateLeft = 0;
				maxHeightInRow = 0;
				maxHeightInRow = bounds.height;
			}
			accumulateLeft += layoutElement.width + this.$hGap;
		}
		measureHeight += maxHeightInRow;
		this.target.setMeasuredSize(measuredWidth, measureHeight);
	}

	public updateDisplayList(unscaledWidth: number, unscaledHeight: number): void {
		super.updateDisplayList(unscaledWidth, unscaledHeight);
		//积累的左部边距和上部边距
		let accumulateLeft = this.$paddingLeft;
		let accumulateTop = this.$paddingTop;
		//当前行的最大高度
		let maxHeightInRow = 0;
		for (var i: number = 0; i < this.target.numChildren; i++) {
			var layoutElement: eui.UIComponent = <eui.UIComponent>(this.target.getElementAt(i));
			if (!egret.is(layoutElement, UIComponentClass) || !layoutElement.includeInLayout) {
				continue;
			}
			if (this.$numRows == 0) this.$numRows = 1;
			if (accumulateLeft + layoutElement.width <= unscaledWidth) {
				maxHeightInRow = Math.max(maxHeightInRow, layoutElement.height);
			} else {
				accumulateTop += maxHeightInRow + this.$vGap;
				accumulateLeft = 0;
				maxHeightInRow = 0;
				this.$numRows++;
			}

			var childX = accumulateLeft;
			var childY = accumulateTop;
			layoutElement.setLayoutBoundsPosition(childX, childY);
			accumulateLeft += layoutElement.width + this.$hGap;
		}
	}

	public set paddingLeft(paddingLeft: number) {
		this.$paddingLeft = paddingLeft;
	}

	public get paddingLeft() {
		return this.$paddingLeft;
	}

	public set paddingTop(paddingTop: number) {
		this.$paddingTop = paddingTop;
	}

	public get paddingTop() {
		return this.$paddingTop;
	}

	public set vGap(vGap: number) {
		this.$vGap = vGap;
	}

	public get vGap() {
		return this.$vGap;
	}

	public set hGap(hGap: number) {
		this.$hGap = hGap;
	}

	public get hGap() {
		return this.$hGap;
	}

	public get numRows() {
		return this.$numRows;
	}
}